﻿
Public Class tcp_pac_talk
    Private ReadOnly _host As String = Nothing
    Private ReadOnly _port As Int32 = 0
    Private client As tcp_client = Nothing
    Private _binded As Boolean = False

    Public Function host() As String
        Return _host
    End Function

    Public Function port() As Int32
        Return _port
    End Function

    Public Sub New(ByVal host As String, ByVal port As Int32)
        assert(Not isemptystring(host))
        assert(port <> 0)
        copy(_host, host)
        copy(_port, port)
        bind()
    End Sub

    Private Sub bind()
        client = New tcp_client()
        _binded = client.bind(host(), port())
    End Sub

    Public Function binded() As Boolean
        Return _binded
    End Function

    Public Function connected() As Boolean
        assert(binded())
        Return client.connected()
    End Function

    Public Sub talk(ByVal d() As Byte, ByVal rtn As pointer(Of bytes), ByRef ec As eventComb)
        ec = talk(d, rtn)
    End Sub

    Public Function talk(ByVal d() As Byte, ByVal rtn As pointer(Of bytes)) As eventComb
        If Not binded() Then
            Return eventComb.failed()
        Else
            Dim ec As eventComb = Nothing
            client.talk(d, rtn, ec)
            Return New eventComb(Function() As Boolean
                                     Return waitfor(ec) AndAlso goto_next()
                                 End Function,
                                 Function() As Boolean
                                     If ec.end_result() Then
                                         Return goto_end()
                                     Else
                                         bind()
                                         Return False
                                     End If
                                 End Function)
        End If
    End Function
End Class
